#!/usr/bin/env python
#coding=utf-8

import os
import wx
#from wx.lib.wordwrap import wordwrap

from gui.notebook import Notebook
from menu import Menu

class MainView(wx.Frame):
    ''' Visual representation of the main gui elements. '''

    def __init__(self):
        '''
        Here first we create the wx.App then we put together all the widgets
        '''
#TODO: MainView should inherit from base view?
        self.app = wx.App(redirect=True)
        wx.Frame.__init__(self, None, size=(650,650),title='pyVoc')
        self.SetBackgroundColour("lightgray")
        self.initStatusBar()
        self.initTaskBarIcon()

        provider = wx.SimpleHelpProvider()
        wx.HelpProvider_Set(provider)


    def create(self, config):
        ''' Create the menu and notebooks.  '''

        menu = Menu(self)
        menu.create_menu()
        self.notebook = Notebook(self)
        self.notebook.create_notebooks(config)

    def export_csv(self, CSVwriter, data, headline, filename):
        ''' Export all vocs in csv file format. '''

        wildcard = "CSV file (*.csv)|*.csv|"
        dlg = wx.FileDialog(
                    self, message="Save file as ...", defaultDir=os.getcwd(),
                    defaultFile=filename, wildcard=wildcard, style=wx.SAVE)
        if dlg.ShowModal() == wx.ID_OK:
            filename = dlg.GetPaths()[0]
            try:
                CSVwriter(data, headline, filename)
            except IOError:
                self.show_message("Couldn't write CSV file")
            else:
                self.show_message('Vocabularies successfully exported')
        dlg.Destroy()

    def initStatusBar(self):
        self.statusbar = self.CreateStatusBar()
        self.statusbar.SetFieldsCount(4)
        self.statusbar.SetStatusWidths([-1,-2,-2,-2])

    def initTaskBarIcon(self):
        image ='gui/icons/languages.gif'
        img = wx.Image(image).ConvertToBitmap()
        icon = wx.EmptyIcon()
        icon.CopyFromBitmap(img)

       #icon = wx.Icon("pycon.ico", wx.BITMAP_TYPE_ICO)
        self.SetIcon(icon)

    def quit(self):
        ''' Destroy the main application window. '''

        self.Destroy()

    def show_about_box(self, version):
        ''' Show a dialog box. '''

        info = wx.AboutDialogInfo()
        info.Name = 'pyVoc'
        info.Version= str(version)
        info.Description = ('This is the prototype of a simple'
            ' to use \n database driven vocabulary trainer based on'
            ' Python and wxPython')#,850, wx.ClientDC(self))
        info.Developers = (u'ralf@schoenian-online.de',)
        info.Copyright = (u'(C) 2008 - 2011 Ralf Schönian')

        popup = wx.AboutBox(info)

    def show_message(self, msg):
        ''' Show a simple message box. '''

        wx.MessageBox(unicode(msg))

    def destroy_splash(self):
        '''Destroys the splash screen after loading the gui.'''
        self.splash.Destroy()
        self.splash = None

    def show_splash_screen(self):
        #wx.Bitmap('gui/icons/document-print.png'))
        #image ='gui/icons/splash_comic.png'
        image ='gui/icons/languages.gif'
        img = wx.Image(image).ConvertToBitmap()
        self.splash = wx.SplashScreen(
            img,
#            wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT,
            wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_NO_TIMEOUT,
            0, # Timer 2000
            None,
            -1
        )
        self.splash.Show()
        wx.Yield()
    def set_backgroundcolour(self, colour):
        ''' Set backrgound colour of the main application window. '''

        self.SetBackgroundColour(colour)

    def set_categories(self, categories):
        '''
        This method contains a small optimisation to take care of the flicker
        that appears during the updates. Exercise: comment out the Freeze
        and Thaw lines and see what happens
        '''
        self.Freeze()
        categories = [category.category for category in categories]

        self.notebook.inputPanel.categoryLst.Set(categories)
        categories.insert(0,'All')
        self.notebook.learnPanel.set_choicelst(categories)
        self.Thaw()

    def set_selected_category(self, idx):
        ''' Select one category by the given index. '''

        self.notebook.learnPanel.categoryChoice.SetSelection(int(idx))

    def update_learn_panel(self, language, config):
        ''' Set the field name according the learning direction. '''

        lang1 = config.get('Settings','lang1')
        lang2 = config.get('Settings','lang2')
        if language == 'lang1':
            self.notebook.learnPanel.update_question_label(lang1)
            self.notebook.learnPanel.update_answer_label(lang2)
        else:
            self.notebook.learnPanel.update_question_label(lang2)
            self.notebook.learnPanel.update_answer_label(lang1)

    def update_statusBar(self, total=0, asked=0, correct=0, wrong=0):
        total = 'Total: %s' %total
        asked = 'Asked: %s' %asked
        right = 'Right: %s' %correct
        wrong = 'Wrong: %s' %wrong

        self.statusbar.SetStatusText(text=total,number=0)
        self.statusbar.SetStatusText(text=asked,number=1)
        self.statusbar.SetStatusText(text=right,number=2)
        self.statusbar.SetStatusText(text=wrong,number=3)

    def start(self):
        ''' Upon start we just show the frame and enter the MainLoop. '''

        self.CenterOnScreen()
        self.Show()
        self.destroy_splash()
        self.app.MainLoop()
